package com.dog.modules.iot.mqtt.codec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES {

	private static final String ALGORITHM = "AES";
	private static final String ALGORITHM_PADDING = "AES/CFB/NoPadding";

	public static byte[] encode(byte[] value, byte[] key, byte[] iv) {
		try {
			IvParameterSpec sr = new IvParameterSpec(iv);
			SecretKeySpec sk = new SecretKeySpec(key, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
			cipher.init(Cipher.ENCRYPT_MODE, sk, sr);
			return cipher.doFinal(value);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static byte[] decode(byte[] value, byte[] key, byte[] iv) {
		try {
			IvParameterSpec sr = new IvParameterSpec(iv);
			SecretKeySpec sk = new SecretKeySpec(key, ALGORITHM);
			Cipher cipher = Cipher.getInstance(ALGORITHM_PADDING);
			cipher.init(Cipher.DECRYPT_MODE, sk, sr);
			return cipher.doFinal(value);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
